#!/usr/bin/env python
# -*- coding: utf-8 -*-

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
from settings import STATIC_PATH

import module.search
import logging
import os
    
class MainHandler(webapp.RequestHandler):   
    def get(self):
        keyword = self.request.get('keyword')       # required
        area = self.request.get('area')             # not required, default *
        providerid = self.request.get('providerid')     # not required, default *
        start = self.request.get('start')           # not required, default 0
        limit = self.request.get('limit')           # not required, default 10
        expired = self.request.get('expired')       # not required, default 1
        action = self.request.get('action')         # not required, default 1
        output = self.request.get('output')         # not required, default xml
        
        # Check data
        if keyword == "":
            keyword = "*" 
        if area == "":
            area = "*" 
        if action == "":
            action = "exact"
        if output == "":
            output = "xml"
            
        providerid = int(providerid) if providerid != "" else 10000
        start = int(start) if start != "" else 0
        limit = int(limit) if limit != "" else 10
        expired = int(expired) if expired != "" else 1
        
        #Memcache          
        #cache_key = "" + keyword +"_"+area+"_" + str(providerid)+"_"+start+"_"+limit+"_"+action+"_"+expired;
        cache_key = "" + keyword +"_"+area+"_" + str(providerid)+"_"+str(start)+"_"+str(limit)+"_"+action+"_"+str(expired);
        
        product_list = memcache.get(cache_key)
        related_keyword = memcache.get("related_keyword"+cache_key)
        if product_list is None:            
            if action == "exact" or keyword == "*":            
                product_list = module.search.SearchProducts.exact_search(keyword, area, providerid, start, limit, expired)
                related_keyword = ""
            else:
                product_list, related_keyword = module.search.SearchProducts.related_search(keyword, area, providerid, start, limit, expired)
                related_keyword = ",".join(related_keyword)
            memcache.add(cache_key, product_list, 3600);
            memcache.add("related_keyword"+cache_key, related_keyword, 3600);
        if related_keyword is None:
            related_keyword = ""
            
        logging.info("Result count: " + str(len(product_list)))
        
        # for XML output
        path = ""
        if(output == "html") :
            self.response.headers['Content-Type'] = 'text/html;charset=UTF-8'
            path = os.path.join(os.path.dirname(__file__), '../templetes/search.html')
            
            for product in product_list:
                if(product.price_now < 0):
                    product.price_now = 0 
                if(keyword != ""):
                    product.title = product.title.replace(keyword, "<span class='search_keyword'>" + keyword + "</span>")
                if(related_keyword != ""):
                    for related_key in related_keyword.split(","):
                        product.title = product.title.replace(related_key, "<span class='search_keyword'>" + related_key + "</span>")
            
            if start != 0 or keyword == "*":
                related_keyword = ""
        else :
            self.response.headers['Content-Type'] = 'text/xml'
            path = os.path.join(os.path.dirname(__file__), '../templetes/search.xml')
            
        self.response.out.write(template.render(path, 
                                                { 
                                                 "static_path" : STATIC_PATH,
                                                 "items": product_list, 
                                                 "keyword": keyword, 
                                                 "related_keyword": related_keyword,
                                                 "area": area, 
                                                 "provider": providerid, 
                                                 "start": start, 
                                                 "limit": limit, 
                                                 "expired": expired}))
        
        

def main():
    application = webapp.WSGIApplication([('/searcher', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()